package com.hjy.scheduled.solr.util;

import com.hjy.scheduled.solr.SolrCacheConfiguration;
import org.apache.solr.client.solrj.impl.HttpSolrClient;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * 原生solr
 * solr连接工具类，使用单例模式（静态内部类）
 */
//@Component
public class SolrUtil implements ApplicationContextAware {
    private static String URL = "";
    private static ApplicationContext applicationContext = null;
    private volatile static HttpSolrClient server = new HttpSolrClient(URL);
    private static class SingletonHolder {
        private static final SolrUtil INSTANCE = new SolrUtil();
    }

    static{
        server.setSoTimeout(100000);
        server.setConnectionTimeout(100000);
        server.setDefaultMaxConnectionsPerHost(100);
        server.setMaxTotalConnections(100);
        server.setFollowRedirects(false);
        server.setAllowCompression(true);
        server.setMaxRetries(1);
    }

    public static SolrUtil getInstance() {
        return SingletonHolder.INSTANCE;
    }

    private SolrUtil(){

    }

    /**
     * 获取solr连接
     * @return
     */
    public HttpSolrClient getServer(){

        if("".equals(URL)){
            SolrCacheConfiguration cacheConfiguration = applicationContext.getBean(SolrCacheConfiguration.class);
            URL = cacheConfiguration.getSolrUrl();
        }
        server.setBaseURL(URL);

        return server;
    }

    /**
     * Bean初始化调用setApplicationContext方法
     * @param applicationContext
     * @throws BeansException
     */
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        if(SingletonHolder.INSTANCE.applicationContext == null){
            SingletonHolder.INSTANCE.applicationContext = applicationContext;
        }
    }

    /**
     * 关闭连接
     * @param solrClient
     */
    public void close(HttpSolrClient solrClient){
        if(solrClient != null){
            try {
                solrClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
